<template>
  <div>
    <div class="params head-form">
      <el-form label-width="auto">
        <div class="params-form">
          <el-form-item label="核销状态">
            <el-select placeholder="请选择" v-model="params.cancelState" style="flex: 1" @change="init">
              <el-option v-for="(item, index) in verificationType" :value="Number(index)" :label="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="调拨编号">
            <el-input v-model="params.slipCode" placeholder="请输入编号" style="flex: 1" @keyup.enter="init" @blur="init" />
          </el-form-item>
          <el-form-item label="调拨金额">
            <input-range v-model="params.amount" @change="init" />
          </el-form-item>
          <el-form-item label="付款账户">
            <el-input v-model="params.payAccount" placeholder="请输入" style="flex: 1" @keyup.enter="init" @blur="init" />
          </el-form-item>
          <el-form-item label="收款账户">
            <el-input v-model="params.receiptAccount" placeholder="请输入" style="flex: 1" @keyup.enter="init" @blur="init" />
          </el-form-item>
          <el-form-item>
            <el-button :icon="RefreshRight" plain type="primary" @click="reset">重置</el-button>
            <el-button :icon="Plus" type="primary" @click="openAdd"> 新建 </el-button>
            <el-button :icon="Download" type="primary" @click="exportTable"> 导出 </el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="table">
      <el-table :data="data" max-height="calc(100vh - 360px)">
        <el-table-column prop="slipApplyId" label="资金申请编号" width="160" />
        <el-table-column prop="slipCode" label="调拨单编号" width="160">
          <template #default="scope">
            {{ scope.row.slipCode || "--" }}
          </template>
        </el-table-column>
        <el-table-column prop="serviceType" label="业务类型">
          <template #default="scope">资金调拨</template>
        </el-table-column>
        <el-table-column prop="city" label="申请状态" width="120">
          <template #default="scope">
            <el-tag type="warning" v-if="scope.row.applyStatus == 1">审核中</el-tag>
            <el-tag type="success" v-else-if="scope.row.applyStatus == 2">已通过</el-tag>
            <el-tag type="primary" v-else-if="scope.row.applyStatus == 3">已打款</el-tag>
            <el-tag type="danger" v-else-if="scope.row.applyStatus == 4">未通过</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="city" label="核销状态" width="120">
          <template #default="scope">
            <template v-if="![1, 4].includes(scope.row.applyStatus)">
              <el-tag type="warning" v-if="scope.row.cancelState == 1">待核销</el-tag>
              <el-tag type="primary" v-else-if="scope.row.cancelState == 2">部分核销</el-tag>
              <el-tag type="success" v-else>已核销</el-tag>
            </template>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="调拨金额" width="120">
          <template #default="scope"> ￥{{ scope.row.applyMoney }} </template>
        </el-table-column>
        <el-table-column prop="address" label="付款账户" width="200">
          <template #default="scope">
            {{ splicing([scope.row.payPayName, scope.row.payAccount, scope.row.payAccountName], "-") }}
          </template>
        </el-table-column>
        <el-table-column prop="zip" label="收款账户" width="200">
          <template #default="scope">
            {{ splicing([scope.row.receivePayName, scope.row.receiveAccount, scope.row.receiveAccountName], "-") }}
          </template>
        </el-table-column>
        <el-table-column prop="transferDate" label="调拨日期" width="250" />
        <el-table-column label="操作" fixed="right" width="250">
          <template #default="scope">
            <el-button type="primary" link size="small" @click="openDetail(scope.row)">详情</el-button>
            <el-button type="primary" link size="small" @click="openAudit(scope.row)" v-if="scope.row.flowInstanceId"
              >审批记录</el-button
            >
            <el-button type="primary" link size="small" v-if="scope.row.slipCode" @click="toPath(scope.row)">支付流水</el-button>
            <el-button type="primary" link size="small" @click="openPay(scope.row)" v-if="scope.row.cancelState == 1"
              >付款</el-button
            >
            <el-button type="primary" link size="small" @click="openDel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty />
        </template>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination
        v-model:current-page="query.current"
        v-model:page-size="query.size"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="init"
        @current-change="init"
      />
    </div>

    <el-dialog v-model="detailVisible" width="500" center align-center :show-close="false">
      <template #title>
        <div class="modal-title">
          <custom-title title="资金调拨单详情" /><el-icon @click="detailVisible = false">
            <Close />
          </el-icon>
        </div>
      </template>
      <div class="detail">
        <div>
          <div>
            编号：<span class="black">{{ detail.slipApplyId }}</span>
          </div>
          <el-tag type="warning" v-if="detail.cancelState == 1">{{ verificationType[detail.cancelState] }}</el-tag>
          <el-tag type="primary" v-else-if="detail.cancelState == 2">{{ verificationType[detail.cancelState] }}</el-tag>
          <el-tag type="success" v-else>{{ verificationType[detail.cancelState] }}</el-tag>
        </div>
        <div>
          调拨金额<span class="black">{{ detail.applyMoney }}</span>
        </div>
        <div>
          创建人<span class="black">{{ detail.createBy }}</span>
        </div>
        <div>
          付款账户<span class="black">{{
            splicing([detail.payPayName, detail.payAccount, detail.receiveAccountName], "-")
          }}</span>
        </div>
        <div>
          收款账户<span class="black">{{
            splicing([detail.receivePayName, detail.receiveAccount, detail.payAccountName], "-")
          }}</span>
        </div>

        <div>
          描述<span class="black">{{ detail.applyDes || "--" }}</span>
        </div>
        <div>
          上传凭证
          <div class="img-list">
            <el-image
              style="width: 80px; height: 80px; border: 1px solid white"
              v-for="item in detailImg"
              :src="item"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="detailImg"
            ></el-image>
          </div>
        </div>
      </div>
    </el-dialog>
    <el-dialog v-model="addVisible" width="500" center align-center :show-close="false" @close="resetForm">
      <template #title>
        <custom-title title="新建" />
      </template>
      <el-form :model="form" label-width="auto" :rules="rules" ref="formRef">
        <el-form-item label="调拨金额" prop="applyMoney">
          <el-input v-model="form.applyMoney" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="付款账户" prop="payAccountId">
          <el-select-v2
            v-model:model-value="form.payAccountId"
            filterable
            remote
            :remote-method="getAccount"
            clearable
            :options="payAccount"
            :props="props"
            placeholder="请输入关键词"
          />
        </el-form-item>
        <el-form-item label="收款账户" prop="receiverAccountId">
          <el-select-v2
            v-model:model-value="form.receiverAccountId"
            filterable
            remote
            :remote-method="getAccount"
            clearable
            :options="account"
            :props="props"
            placeholder="请输入关键词"
          />
        </el-form-item>
        <el-form-item label="描述" prop="applyDes">
          <el-input v-model="form.applyDes" type="textarea" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="上传凭证" prop="fileVos">
          <div>
            <el-upload class="avatar-uploader" multiple :show-file-list="false" :http-request="addCustomRequest">
              <div class="list">
                <div class="code" v-for="item in form.fileVos" :key="item">
                  <img :src="item.fileUrl" />
                  <div class="del">
                    <el-icon @click.stop="delAddImg(item)">
                      <DeleteFilled />
                    </el-icon>
                  </div>
                </div>
                <el-icon class="upload" v-if="form.fileVos.length < 6">
                  <Plus />
                  <span>点击上传</span>
                </el-icon>
              </div>
            </el-upload>
            <div class="tip">注：支持{{ fileType }}格式，单张大小不超过{{ maxSize }}MB，只支持{{ maxCount }}张</div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addVisible = false">取消</el-button>
          <el-button type="primary" @click="comfirm"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="payVisible" width="600" center align-center :show-close="false" @close="resetPay">
      <template #title>
        <custom-title title="发起调拨" />
      </template>
      <div class="info">
        调拨单号：<span>{{ detail.slipApplyId }}</span>
        <div class="card">
          <div>
            <div>
              <div>应付金额</div>
              <div>￥{{ detail.plainMoney }}</div>
            </div>
            <div>
              <div>已付金额</div>
              <div>￥{{ detail.inMoney }}</div>
            </div>
            <div>
              <div>未付金额</div>
              <div>￥{{ detail.outMoney }}</div>
            </div>
          </div>
        </div>
      </div>
      <el-form :model="payForm" label-position="top" ref="payFormRef" :rules="payRules">
        <el-form-item label="调拨日期" prop="receiptDate">
          <el-date-picker
            style="flex: 1"
            v-model="payForm.receiptDate"
            type="date"
            placeholder="请选择"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="付款账户" prop="accountId">
          <div class="preview">
            {{ splicing([detail.payPayName, detail.payAccount, detail.payAccountName], "-") }}
          </div>
        </el-form-item>
        <el-form-item label="收款账户" prop="accountId">
          <div class="preview">
            {{ splicing([detail.receivePayName, detail.receiveAccount, detail.receiveAccountName], "-") }}
          </div>
        </el-form-item>
        <el-form-item label="支付凭证" prop="fileVos">
          <div>
            <el-upload class="avatar-uploader" multiple :show-file-list="false" :http-request="customRequest">
              <div class="list">
                <div class="code" v-for="item in payForm.fileVos" :key="item">
                  <img :src="item.fileUrl" />
                  <div class="del">
                    <el-icon @click.stop="delImg(item)">
                      <DeleteFilled />
                    </el-icon>
                  </div>
                </div>
                <el-icon class="upload" v-if="payForm.fileVos.length < 6">
                  <Plus />
                  <span>点击上传</span>
                </el-icon>
              </div>
            </el-upload>
            <div class="tip">注：支持{{ fileType }}格式，单张大小不超过{{ maxSize }}MB，只支持{{ maxCount }}张</div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="payVisible = false">取消</el-button>
          <el-button type="primary" @click="payComfirm"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="delVisible" width="400" center align-center :show-close="false">
      <div class="sure">
        <div>
          <el-icon>
            <Warning />
          </el-icon>
        </div>
        <span>此调拨单将被删除，是否继续？</span>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="delVisible = false">取 消</el-button>
          <el-button type="primary" @click="delItem">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <Audit v-model:show="visibleAudit" v-if="visibleAudit" :code="code" @success="init" />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { RefreshRight, Plus, Download } from "@element-plus/icons-vue";
import { getAdvancePaymentTree, exportAllocation } from "@/apis/invoices";
import { ElMessage } from "element-plus";
import { getList as getMyAccountList } from "@/apis/myAccount";
import { splicing, cleanArray } from "@/utils";
import { verificationType } from "@/utils/config";
import { useRoute } from "vue-router";
import uploadFile from "@/utils/uploadFile";
import { getList, del, add, pay } from "@/apis/invoices/allocate";
import Audit from "@/views/audit";
import exportExcel from "@/utils/exportExcel";

const route = useRoute();
const visibleAudit = ref(false);
const code = ref();
const emit = defineEmits(["toPayment"]);
const toPath = item => {
  emit("toPayment", {
    slipCode: item.slipCode,
    slipType: 10
  });
};
const resetForm = () => {
  formRef.value.resetFields();
  form.value = {
    fileVos: []
  };
};

const detailImg = computed(() => {
  return detail.value.applyPicUrls ? detail.value.applyPicUrls.split(",") : [];
});
const props = {
  label: "accountName",
  value: "accountId"
};
const account = ref([]);
const payAccount = ref([]);
const formRef = ref(null);
const payFormRef = ref(null);
const categoryOptions = ref([]);
const query = ref({
  current: 1,
  size: 10
});
const params = ref({
  slipCode: route.query.slipCode
});
const reset = () => {
  params.value = {};
  init();
};
const resetPay = () => {
  payFormRef.value.resetFields();
  payForm.value = {
    fileVos: []
  };
};
const detailVisible = ref(false);
const addVisible = ref(false);
const payVisible = ref(false);
const delVisible = ref(false);

const form = ref({
  fileVos: []
});
const payForm = ref({
  fileVos: []
});
const delId = ref("");
const detail = ref({});
const total = ref(0);
const data = ref([]);
const rules = {
  applyMoney: [
    { required: true, message: "请输入金额", trigger: "blur" },
    { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: "请输入正确的金额", trigger: "blur" }
  ],
  payAccountId: [{ required: true, message: "请选择付款账户", trigger: "blur" }],
  receiverAccountId: [{ required: true, message: "请选择收款账户", trigger: "blur" }],
  applyDes: [{ max: 100, message: "描述不能大于100字符" }]
};
const payRules = {
  payType: [{ required: true, message: "请选择支付方式", trigger: "blur" }],
  receiptDate: [{ required: true, message: "请选择收款日期", trigger: "blur" }],
  fileVos: [{ required: true, message: "请上传收款凭证", trigger: "blur" }],
  money: [
    { required: true, message: "请输入收款金额", trigger: "blur" },
    { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: "请输入正确的金额", trigger: "blur" }
  ]
};
const delImg = img => {
  payForm.value.fileVos = payForm.value.fileVos.filter(item => item.fileId != img.fileId);
};
const delAddImg = img => {
  form.value.fileVos = form.value.fileVos.filter(item => item.fileId != img.fileId);
};
/**
 * 打开审批弹窗
 */
const openAudit = item => {
  visibleAudit.value = true;
  code.value = item.flowInstanceId;
};
const openDel = item => {
  delId.value = item.slipApplyId;
  delVisible.value = true;
};
const delItem = async () => {
  try {
    await del(delId.value);
    init();
    ElMessage.success("删除成功");
    delVisible.value = false;
  } catch (error) {}
};
const openDetail = async item => {
  detail.value = { ...item };
  detailVisible.value = true;
};
const openAdd = () => {
  addVisible.value = true;
};
const openPay = item => {
  isImgMax.value = false;
  payVisible.value = true;
  detail.value = { ...item };
};
const isImgMax = ref(false);
const imgRules = options => {
  const type = ["image/jpg", "image/jpeg", "image/png"];
  const { file } = options;
  if (!type.includes(file.type)) {
    ElMessage.error("图片格式错误");
    return false;
  } else if (file.size / 1024 / 1024 > maxSize.value) {
    ElMessage.error(`图片大小不能超过${maxSize.value}MB!`);
    return false;
  }
  return true;
};

const fileType = ref("JPG/JPEG/PNG");
const maxSize = ref(20);
const maxCount = ref(6);
const customRequest = async options => {
  if (!imgRules(options)) return;
  const fileInfo = await uploadFile(options);
  if (payForm.value.fileVos.length < maxCount.value) {
    payForm.value.fileVos.push({ fileUrl: fileInfo.url, fileName: fileInfo.name, fileId: fileInfo.uid });
  } else {
    if (!isImgMax.value) ElMessage.error(`最多上传${maxCount.value}张图片`);
    isImgMax.value = true;
  }
};

const addCustomRequest = async options => {
  if (!imgRules(options)) return;
  const fileInfo = await uploadFile(options);
  if (form.value.fileVos.length < maxCount.value) {
    form.value.fileVos.push({ fileUrl: fileInfo.url, fileName: fileInfo.name, fileId: fileInfo.uid });
  } else {
    if (!isImgMax.value) ElMessage.error(`最多上传${maxCount.value}张图片`);
    isImgMax.value = true;
  }
};
const comfirm = () => {
  formRef.value.validate(async valid => {
    if (!valid) return;
    try {
      await add({ ...form.value, type: undefined });
      addVisible.value = false;
      init();
      ElMessage.success("操作成功");
    } catch (error) {}
  });
};
const payComfirm = () => {
  payFormRef.value.validate(async valid => {
    if (!valid) return;
    try {
      await pay({
        ...payForm.value,
        receiptDate: payForm.value.receiptDate ? payForm.value.receiptDate + " 00:00:00:" : undefined,
        type: undefined,
        slipId: detail.value.slipId
      });
      payVisible.value = false;
      init();
      ElMessage.success("操作成功");
    } catch (error) {}
  });
};
const getParams = () => {
  const minAmount = params.value.amount ? params.value.amount[0] : undefined;
  const maxAmount = params.value.amount ? params.value.amount[1] : undefined;
  const paramsData = {
    ...params.value,
    minAmount,
    maxAmount
  };
  delete paramsData.amount;
  return paramsData;
};
const init = async () => {
  const {
    data: { list = [], total: totalNum = 0 }
  } = await getList(query.value, getParams());
  data.value = list;
  total.value = totalNum;
};
const exportTable = async () => {
  try {
    const res = await exportAllocation(query.value, getParams());
    exportExcel(res, "调拨单列表");
  } catch (error) {}
};
const getCategory = async () => {
  const res = await getAdvancePaymentTree();
  categoryOptions.value = res.data;
};
const getAccount = async key => {
  const { data: { list = [] } = {} } = await getMyAccountList({ current: 1, size: 100000 }, { status: 1, account: key });
  const accountList = list.map(v => ({ ...v, accountName: splicing(cleanArray([v.dictName, v.account, v.accountName]), "-") }));
  account.value = accountList;
  payAccount.value = accountList;
};
onMounted(() => {
  init();
  getCategory();
});
</script>

<style lang="scss" scoped>
@import "../comon.scss";

.params {
  .params-form {
    grid-template-columns: repeat(4, 1fr);
  }
}
</style>
